package com.base.core.action.keywords;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.base.core.BaseAction;
import com.base.core.util.NetUtil;
import com.base.core.util.StringUtil;

@SuppressWarnings("serial")
public class GetBaiduRelateWordsAction extends BaseAction{
	
	private String searchWord="";

	public String getSearchWord() {
		return searchWord;
	}

	public void setSearchWord(String searchWord) {
		this.searchWord = searchWord;
	}
	
	private List<String> relateWords = new ArrayList<String>();

	public List<String> getRelateWords() {
		return relateWords;
	}

	public void setRelateWords(List<String> relateWords) {
		this.relateWords = relateWords;
	}

	public static void main(String[] args) throws UnsupportedEncodingException{
		Long start = System.currentTimeMillis();
		String sword ="电影";
		String swordUTF8 =java.net.URLEncoder.encode(sword,"utf-8");
		System.out.println(swordUTF8);
		String results =new NetUtil().getTargetStr(
				"http://suggestion.baidu.com/su?wd="+sword+"&p=3&cb=window.bdsug.sug",
				"gb2312");
		System.out.println("#########baidu---百度#########");
		System.out.println(results);
		if(results.indexOf("[")!=-1 && results.indexOf("]")!=-1){
			int bstart =results.indexOf("[");
			int bend =results.indexOf("]");
			System.out.println(results.substring(bstart+1, bend));
		}
//		results =new NetUtil().getTargetStr(
//		"http://www.google.com.hk/complete/search?client=hp&hl=zh-CN&authuser=0&cp=2&q="+swordUTF8+"&xhr=t","utf-8");
//		System.out.println("#########google---谷歌#########");
//		System.out.println(results);
        
//		results =new NetUtil().getTargetStr(
//			"http://www.yahoo.cn/ajax.php?q="+swordUTF8+"&limit=10&timestamp="+new Date().getTime(),"utf-8");
//        System.out.println("#########yahoo---雅虎#########");
//        System.out.println(results);
        
        results =new NetUtil().getTargetStr("http://www.soso.com/wh.q?w="+sword,"gb2312");
        System.out.println("#########soso---搜搜#########");
        System.out.println(results);
        System.out.println(results.replaceAll("0", "").replaceAll("00", "").replaceAll("\\s+", ","));
        
        results =new NetUtil().getTargetStr("http://www.youdao.com/suggest2/suggest.s?query="+swordUTF8+"&keyfrom=web.index.suggest&o=aa&rn=10&h=11","utf-8");
        System.out.println("#########有道---youdao#########");
        System.out.println(results);
        if(results.indexOf("[")!=-1 && results.indexOf("]")!=-1){
			int bstart =results.indexOf("[");
			int bend =results.indexOf("]");
			System.out.println(results.substring(bstart+1, bend).replaceAll("\\{c:", "").replaceAll("}", ""));
		}
        
        results =new NetUtil().getTargetStr("http://sugg.sogou.com/sugg/ajaj_json.jsp?key="+sword+"&type=web&pr=web","gb2312");
        System.out.println("#########soso---搜搜#########");
        System.out.println(results);
        if(results.indexOf(",[")!=-1 && results.indexOf("]")!=-1){
			int bstart =results.indexOf(",[");
			int bend =results.indexOf("]");
			System.out.println(results.substring(bstart+2, bend));
		}
        
        results =new NetUtil().getTargetStr("http://bj1.api.bing.com/qsonhs.aspx?FORM=ASAPIH&mkt=zh-CN&type=cb&cb=sa_inst.apiCB&q="+swordUTF8+"&cp=2&o=s","utf-8");
        System.out.println("#########bing---必应#########");
        System.out.println(results);
        if(results.indexOf(":[{\"Txt\":")!=-1 && results.indexOf("]")!=-1){
			int bstart =results.indexOf(":[{\"Txt\":");
			int bend =results.indexOf("}]}}");
			results =results.substring(bstart+2, bend-1);
			String[] ags =results.split(",\\{");
			results ="";
			for(String str:ags){
				bstart =str.indexOf(":");
				bend =str.indexOf(",");
				results +=str.substring(bstart+1,bend)+",";
				continue;
			}
		}
        System.out.println(results);
        
        results =new NetUtil().getTargetStr("http://www.baidu.com/s?wd="+sword,"gb2312");
        Pattern pattern = Pattern.compile("(.*)<div id=\"rs\"><table cellpadding=\"0\"><tr><th rowspan=\"2\" class=\"tt\">相关搜索</th>(.*)<div id=\"search\"><form name=\"f2\" action=\"/s\" >(.*)");
		Matcher mat = pattern.matcher(results);
		String rs ="";
		if(mat.find()){
			rs =mat.group(2);
			System.out.println(rs);
			if(!StringUtil.isEmpty(rs)){
				rs = rs.replaceAll("\\</a>", ",").replaceAll("<([^>]*)>", "");
			}
		}
		System.out.println(rs);
        
        Long end = System.currentTimeMillis();
        System.out.println(end-start);
	}
	
	@SuppressWarnings("unchecked")
	public String execute(){
        try{		
		String swordUTF8 ="";
		Set<String> sets = new HashSet<String>();
		try {
			swordUTF8 = java.net.URLEncoder.encode(searchWord,"utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String results =new NetUtil().getTargetStr(
				"http://suggestion.baidu.com/su?wd="+searchWord+"&p=3&cb=window.bdsug.sug",
				"gb2312");
		if(!StringUtil.isEmpty(results) && results.indexOf("[")!=-1 && results.indexOf("]")!=-1){
			int bstart =results.indexOf("[");
			int bend =results.indexOf("]");
			results =results.substring(bstart+1, bend);
			String[] rs = results.replaceAll("\"", "").split(",");
			sets = new HashSet(Arrays.asList(rs));
		}
//		results =new NetUtil().getTargetStr(
//		"http://www.google.com.hk/complete/search?client=hp&hl=zh-CN&authuser=0&cp=2&q="+swordUTF8+"&xhr=t","utf-8");
//		System.out.println("#########google---谷歌#########");
//		System.out.println(results);
        
//		results =new NetUtil().getTargetStr(
//			"http://www.yahoo.cn/ajax.php?q="+swordUTF8+"&limit=10&timestamp="+new Date().getTime(),"utf-8");
//        System.out.println("#########yahoo---雅虎#########");
//        System.out.println(results);
		String[] rs = new String[]{};
        results =new NetUtil().getTargetStr("http://www.soso.com/wh.q?w="+searchWord,"gb2312");
        if(!StringUtil.isEmpty(results)){
        results =results.replaceAll("0", "").replaceAll("00", "").replaceAll("\\s+", ",");
        rs=results.split(",");
        for(String str:rs){
          if(!StringUtil.isEmpty(str))
        	sets.add(str);
        }
        }
        
        results =new NetUtil().getTargetStr("http://www.youdao.com/suggest2/suggest.s?query="+swordUTF8+"&keyfrom=web.index.suggest&o=aa&rn=10&h=11","utf-8");
        if(!StringUtil.isEmpty(results) && results.indexOf("[")!=-1 && results.indexOf("]")!=-1){
			int bstart =results.indexOf("[");
			int bend =results.indexOf("]");
			results =results.substring(bstart+1, bend).replaceAll("\\{c:", "").replaceAll("}", "");
			rs=results.split(",");
	        for(String str:rs){
	          if(!StringUtil.isEmpty(str))
	        	sets.add(str.replaceAll("'", ""));
	        }
        }
        
        results =new NetUtil().getTargetStr("http://sugg.sogou.com/sugg/ajaj_json.jsp?key="+searchWord+"&type=web&pr=web","gb2312");
        if(!StringUtil.isEmpty(results) && results.indexOf(",[")!=-1 && results.indexOf("]")!=-1){
			int bstart =results.indexOf(",[");
			int bend =results.indexOf("]");
			results =results.substring(bstart+2, bend);
			rs=results.split(",");
	        for(String str:rs){
	          if(!StringUtil.isEmpty(str))
	        	sets.add(str.replaceAll("\"", ""));
	        }
		}
        
        results =new NetUtil().getTargetStr("http://bj1.api.bing.com/qsonhs.aspx?FORM=ASAPIH&mkt=zh-CN&type=cb&cb=sa_inst.apiCB&q="+swordUTF8+"&cp=2&o=s","utf-8");
        if(!StringUtil.isEmpty(results) && results.indexOf(":[{\"Txt\":")!=-1 && results.indexOf("]")!=-1){
			int bstart =results.indexOf(":[{\"Txt\":");
			int bend =results.indexOf("}]}}");
			results =results.substring(bstart+2, bend-1);
			String[] ags =results.split(",\\{");
			results ="";
			for(String str:ags){
				bstart =str.indexOf(":");
				bend =str.indexOf(",");
				results +=str.substring(bstart+1,bend)+",";
			}
			rs=results.split(",");
	        for(String str:rs){
	          if(!StringUtil.isEmpty(str))
	        	sets.add(str.replaceAll("\"", ""));
	        }
		}
		relateWords.addAll(sets);
		List<String> arrays = new ArrayList<String>();
		for(int i=0;i<relateWords.size();i++){
			arrays.add(relateWords.get(i).replaceAll("\\s+","").replaceAll("\\+", ""));
		}
		relateWords = arrays;
        }catch(Exception e){
        }
        return SUCCESS;
	}
	
	@SuppressWarnings("unchecked")
	public void distinctArray(List list){
	for (int i = 0; i < list.size() - 1; i++) {
	    for (int j = list.size() - 1; j > i; j--) {
	     if (list.get(j).equals(list.get(i))) {
	      list.remove(j);
	     }
	    }
	   }
	}
	
	public String input(){
		return SUCCESS;
	}
}
